/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "adc.h"
#include "4g.h"
#include "lowpower.h"
#include "temp.h"
#include "sport.h"
#include "line_monitor.h"
#include "stdio.h"
#include <string.h>
#include <stdlib.h>
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
typedef struct {
    float latitude;
    float longitude;
    float temperature;
    int motion;
    float battery_level;
    uint32_t timestamp;
} SensorData;
/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
void EG800ZSensorData(SensorData *data);
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
extern UART_HandleTypeDef huart2;
/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_USART2_UART_Init();
	//MX_ADC_Init();
  /* USER CODE BEGIN 2 */
	/*uint16_t adc_raw;
	float voltage;*/
//	printf("System Start...\r\n");
//	printf("=== Low Power System Starting ===\r\n");
//	printf("Mode: Work 2s + Sleep 5s (Testing)\r\n");
//	printf("=== �͹���ϵͳ���� ===\r\n");

	// 注意：PA6是运动传感器的SDO引脚，用于选择I2C地址
	// 不要锁定这个引脚，否则会影响地址选择
	// 如果需要使用其他引脚作为锁定引脚，请修改这里


	//��ʼ���¶ȴ�����
	temp_init();
	printf("[TEMP] DS18B20 initialized\r\n");
//
//	//��ʼ���˶�������
	sport_init();
	choose_comm_type(IIC);        // 选择I2C通信        // ѡ��I2Cͨ��
//
//	// ���SDO��GND: 0x18, ���SDO��VCC: 0x19
	choose_addr(0x18);            // 根据硬件连接选择地址            // �������Ӳ�����ӵ���
//
	sport_config();               // 配置传感器               // ���ô�����
	printf("[MOTION] LIS3DHTR initialized (I2C: 0x%02X)\r\n", sport_addr);
//
//	// ��ʼ����·���
////	LineMonitor_Init();
//	printf("[ϵͳ] ��ȫ���ϵͳ������\n");
//
//	// ��ʼ��4Gģ��
////  EG800Z_Init();
//  printf("[4G] EG800Z initialized\r\n");
//
////	LowPower_Init();
//	printf("ģʽ: ����2�� + ˯��5��\r\n");
//
//	// ����4Gģ��
//  printf("[4G] Powering on...\r\n");
  //EG800Z_PowerOn();
  //HAL_Delay(10000);  // �ȴ�ģ������

  // ����MQTT����
//  printf("[4G] Establishing MQTT connection...\r\n");
  //EG800Z_EstablishConnection();

	uint8_t test_data = 0;
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
		 // ��ȫ��� - ������ȼ�
//    if (line_disconnected) {
//        printf("[ϵͳ] ��ȫ��������\n");
//        LineMonitor_ProcessAlarm();
//        line_disconnected = 0;
//		}
		// �����׶�

//    printf("[����]%d\r\n",DS18B20_Get_Temp());
//
		int motion = LIS3DHTR_CheckMovement();
		printf("[MOTION] Status: %d\r\n", motion);
		HAL_Delay(5000);
//		 float voltage;
//    SensorData data;
//
//    // ��ȡ��ص�ѹ
//    voltage = LowPower_ReadBatteryVoltage();
//    printf("[BATTERY] Voltage: %.2fV\r\n", voltage);
//
//		// ����4Gģ������
//    EG800Z_Process();
//
//    if (LowPower_IsBatteryLow())
//			{
//        printf("[����] ��ص�ѹ���ͣ��������ι���\r\n");
//			}
//		else {
//    // ������������...
//				printf ("=== �������� ===\r\n");
//				Peripherals_PowerOn();
//
//				printf("[SENSOR] �ɼ�����������...\r\n");
//
//    data.latitude = GPS_GetLatitude();           // ��ʵGPSγ��
//    data.longitude = GPS_GetLongitude();         // ��ʵGPS����
//    data.temperature = TempSensor_ReadTemperature(); // ��ʵ�¶�
//    data.motion = MotionSensor_ReadStatus();     // ��ʵ�˶�״̬
//    data.battery_level = voltage;
//    data.timestamp = HAL_GetTick();
//
//    printf("[SENSOR] ���ݲɼ����: Lat=%.4f, Lon=%.4f, Temp=%.1f��C, Motion=%d\r\n",
//             data.latitude, data.longitude, data.temperature, data.motion);
//
//			// �������ݵ�MQTT
//			EG800ZSensorData(&data);
//
//				//�ر�����
//				printf ("=== �ر����� ===\r\n");
//				Peripherals_PowerOff();
//    }
//
//    HAL_Delay(1800000);
//    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, GPIO_PIN_RESET);
//
//    printf("[˯��] ����˯��...\r\n");
//
//    // ʹ��ģ�黯��˯�ߺ���
//    LowPower_EnterSleep(3420);  // ˯��57����
//
//    printf("[����] ϵͳ����!\r\n");
//    printf("----------------------------------------\r\n");
		/* USER CODE END WHILE */
    /* USER CODE BEGIN 3 */
  /* USER CODE END 3 */

}
}
/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
  RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};

  /** Configure the main internal regulator output voltage
  */
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLLMUL_8;
  RCC_OscInitStruct.PLL.PLLDIV = RCC_PLLDIV_2;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK)
  {
    Error_Handler();
  }
  PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USART2;
  PeriphClkInit.Usart2ClockSelection = RCC_USART2CLKSOURCE_PCLK1;
  if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */
/**
  * @brief �򵥵ĵ�ص�ѹ��ȡ
  */

//  ȷ���������ֻ����һ�Σ�
static void EG800ZSensorData(SensorData* data)
{
	// ת��ΪMQTT��Ҫ�����ݽṹ
    SensorData_t mqtt_data;
    mqtt_data.latitude = data->latitude;
    mqtt_data.longitude = data->longitude;
    mqtt_data.temperature = data->temperature;
    mqtt_data.motion = (uint8_t)data->motion;
    mqtt_data.battery_level = (uint8_t)(data->battery_level * 10); // ת��Ϊ�ٷֱȽ���ֵ
    mqtt_data.timestamp = data->timestamp;
    printf("[4G] Sending: Lat=%.4f, Lon=%.4f, Temp=%.1f��C, Bat=%.2fV\r\n",
           data->latitude, data->longitude, data->temperature, data->battery_level);
		// ͨ��MQTT��������
    EG800Z_MQTT_PublishSensorData(&mqtt_data);
}

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}
// ��main.c�ļ���������к���֮������


#ifdef USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
